package cn.com.callback

import groovy.json.*;
import java.util.Map;

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

import java.text.ParseException
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import cn.com.elite.EliteBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

import cn.com.elite.Util;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;


/**
 *
 * @Title: Bp_Api_Get_CGCaseList
 * @Description: 宝安排水 同步数字化案件基本信息（用于市属责任单位）同步案件的基本信息
 *
 * @author: chieh
 * @date 2020-07-29 12:30:00
 *
 */

public class Bp_Api_Get_CGCaseList implements ServiceBackInvoke{
	private static final Log log = LogFactory.getLog(Bp_Api_Get_CGCaseList.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response) {
		def szhtokresult =eliteBean.chaxun_sql("select PARAMETERVALUE from SYSC_PARAMETER where PARAMETER_ID = 'SZHTOK' and MODIFIEDDATE>dateadd(minute,-1,GETDATE())", "dataSource");
		def szhtok;
		if(szhtokresult.size() > 0) {
			szhtok = szhtokresult.get(0).get("PARAMETERVALUE");
			log.debug("szhtok:	"+szhtok);
		}
		if(szhtok==null){
			szhtok=getCaseTasks(eliteBean);
		}
		log.debug("szhtok1:	"+szhtok);
		
		getCaseList(eliteBean,szhtok);
		return "同步成功";
	}

	// 同步案件待办信息
	public void getCaseList(EliteBean eliteBean,String szhtok){

		String logPrefix = "同步案件待办信息-";
		log.debug(logPrefix + "开始...");
		//默认从第1页开始调度
		boolean onofftype =true;
		int PageIndex = 1;
		int count=0;
		long rstartTime,rendTime;
		rstartTime = System.currentTimeMillis();
		log.debug(logPrefix + "开始处理时间:" + rstartTime);
		while(onofftype && PageIndex < 10){
			try {
				String URL = getProperty.get("SZCG.URL")+"/swEvent/GetEvtTodolist?access_token="+szhtok;
				
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				Calendar c = Calendar.getInstance();
				Calendar cd = Calendar.getInstance();
				//前一个月 和当前时间 2020-06-30、2020-07-30
				c.setTime(new Date());
				c.add(Calendar.MONTH, -1);
				Date m = c.getTime();
				String beginDate = format.format(m);
				//String endDate =format.format(new Date()).toString();
				cd.add(Calendar.DAY_OF_MONTH, 1);
				String endDate =format.format(cd.getTime());
				//String beginDate = "2020-05-01";
				//String endDate ="2020-09-01";
				String json ="{beginDate:\""+beginDate+"\",endDate:\""+endDate+"\",evtCode:\"\",types:2,PageIndex:"+PageIndex+",PageSize:100}";
				
				// 设置头文件
				Map<String, String> headMap = new HashMap<String, String>();
				headMap.put("Content-Type", "application/json");

				log.debug(logPrefix + "调用地址URL：" + URL);
				log.debug(logPrefix + "调用发送报文信息：" + json);
				String reJson = Util.doHttpPostUseHead(URL, json, "UTF-8", 100000, 0, headMap);
				
				log.debug(logPrefix + "调用返回信息：" + reJson.toString());
				JSONObject inObject = new JSONObject(reJson);
				String statusCode = KHUtil.GetJV(inObject, "statusCode");
				String errorMsg = KHUtil.GetJV(inObject, "errorMsg");
				String result = KHUtil.GetJV(inObject, "result");

				if(statusCode.equals("0")) {
					JSONObject resultObject = new JSONObject(result);
					count = Integer.valueOf(KHUtil.GetJV(resultObject, "count"));
					String datesObject = KHUtil.GetJV(resultObject, "dates");

					JSONArray arrJsonArray = new JSONArray(datesObject);
					int arrInt = arrJsonArray.length();
					log.debug("接入List数量:" + arrInt);

					for (int i = 0; i < arrInt; i++) {

						JSONObject arrCustJson = arrJsonArray.getJSONObject(i);

						//获取案件信息
						String evtID = GetJV(arrCustJson, "evtID");//案件ID
						String className = GetJV(arrCustJson, "className");//案件类型
						String mapName = GetJV(arrCustJson, "mapName");//案件区域
						String evtTile = GetJV(arrCustJson, "evtTile");//案件号
						String jdSyStr = GetJV(arrCustJson, "jdSyStr");//剩余时间
						String inDate = GetJV(arrCustJson, "inDate");//来件时间
						String desc = GetJV(arrCustJson, "desc");//案件描述
						String sourcename = GetJV(arrCustJson, "sourcename");//案件来源
						String actinstid = GetJV(arrCustJson, "actinstid");//流程环节ID
						String wfinstid = GetJV(arrCustJson, "wfinstid");//案件流程ID
						String lastzrdw = GetJV(arrCustJson, "lastzrdw");//处置对象
						String activityName = GetJV(arrCustJson, "activityName");//当前处置流程
						String address = GetJV(arrCustJson, "address");//事发位置
						String baidu_x = GetJV(arrCustJson, "baidu_x");//百度坐标X
						String baidu_y = GetJV(arrCustJson, "baidu_y");//百度坐标Y
						String limit = GetJV(arrCustJson, "limit");//环节时限：单位（秒）  0：不设时限
						
						String ActivityInstances = GetJV(arrCustJson, "ActivityInstances");
						String communityID = GetJV(arrCustJson, "communityID");
						
						String status = GetJV(arrCustJson, "status");

						//查询现有当前工单编号是否存在现有工单
						def getSelectSQL = eliteBean.chaxun_sql("select top 1 o.createddate as createddate,o.workorderid as workorderid,t.Relation_ID as Relation_ID,o.curstep_id_map as curstep_id_map,o.objectivestatus as objectivestatus,t.workorder_state as workorder_state,bw.status as resultstatus from TABCCONSULTWORKORDER t LEFT JOIN objective o on t.Relation_ID=o.objective_guid LEFT JOIN BP_workordertask bw ON bw.objective_guid = t.Relation_ID where o.workorderid= '" + evtTile + "' order by bw.modifytime desc", "dataSource");
						log.debug("查询当前同步的工单是否已经存在 SQL:" + getSelectSQL + " 结果数量:" + getSelectSQL.size());

						String createddate = null;
						String old_Relation_ID = null;
						String curstep_id_map = null;
						String objectivestatus = null;
						String workorder_state = null;
						String resultstatus = null;
						if(getSelectSQL.size() > 0) {
							createddate = getSelectSQL.get(0).get("createddate");
							old_Relation_ID = getSelectSQL.get(0).get("Relation_ID");
							curstep_id_map = getSelectSQL.get(0).get("curstep_id_map");
							objectivestatus = getSelectSQL.get(0).get("objectivestatus");
							workorder_state = getSelectSQL.get(0).get("workorder_state");
							resultstatus = getSelectSQL.get(0).get("resultstatus");
						}else{
							old_Relation_ID = null;
						}
						
						//获取附件信息
						JSONArray beforeImgJsonArray = arrCustJson.getJSONArray("beforeImg");
						JSONArray afterImgJsonArray = arrCustJson.getJSONArray("afterImg");
						String beforeImgevtID = "";
						String beforeImgfileUrl = "";
						String beforeImgfileID = "";
						String afterImgevtID = "";
						String afterImgfileUrl = "";
						String afterImgfileID = "";
						
						if(old_Relation_ID == null || old_Relation_ID.length() <= 0) {
							String Relation_ID = UUID.randomUUID().toString();
							//处理前附件列表 1  type 处理前
							for (int j = 0; j < beforeImgJsonArray.length(); j++) {
								JSONObject beforeImgJson = beforeImgJsonArray.getJSONObject(j);
								beforeImgevtID = GetJV(beforeImgJson, "evtID");
								beforeImgfileUrl = GetJV(beforeImgJson, "fileUrl");
								beforeImgfileID = GetJV(beforeImgJson, "fileID");
								eliteBean.update("insert into rm_uploadrecord(guid,objectiveID,path,name,operator,operationtime,filedesc,type)VALUES(NEWID(),'" + Relation_ID + "','" + beforeImgfileUrl + "','" + beforeImgevtID + "','数字化城管',GETDATE(),'" + beforeImgfileID + "','1')", "dataSource");
							}
							//处理后附件列表 2  type 处理后
							for (int j = 0; j < afterImgJsonArray.length(); j++) {
								JSONObject afterImgJson = afterImgJsonArray.getJSONObject(j);
								afterImgevtID = GetJV(afterImgJson, "evtID");
								afterImgfileUrl = GetJV(afterImgJson, "fileUrl");
								afterImgfileID = GetJV(afterImgJson, "fileID");
								eliteBean.update("insert into rm_uploadrecord(guid,objectiveID,path,name,operator,operationtime,filedesc,type)VALUES(NEWID(),'" + Relation_ID + "','" + afterImgfileUrl + "','" + afterImgevtID + "','数字化城管',GETDATE(),'" + afterImgfileID + "','2')", "dataSource");
							}
							//插入数据
							String[] data = new String[4];
								data[0] ="insert into TABCCONSULTWORKORDER(RELATION_ID,business_source,case_type,case_region,case_id,surplus_time,come_time,case_describe,disposal_object,disposal_process,address,location_x,location_y,limit_time,actinstid,wfinstid,evtID,workorder_state)VALUES('" + Relation_ID + "','9999B1','" + className + "','" + mapName + "','" + evtTile + "','" + jdSyStr + "','" + inDate + "','" + desc + "','" + lastzrdw + "','" + activityName + "','" + address + "','" + baidu_x + "','" + baidu_y + "','" + limit + "','" + actinstid + "','" + wfinstid + "','" + evtID + "','1')";
								data[1] = "Insert Into Objective (Objective_Guid, Objectivetype_Id, Handleby_Id, Handlegroup_Id, Priority_Id, Expireddate, Customer_Guid, Objectivestatus,comments, Createdby, Createddate, Modifiedby, Modifieddate, Workorderframe_Id, Category, Forecastdate, Workorderid, Objectivesubstatus, Map_Id, Curstep_Id_Map) Values ('" + Relation_ID + "', 'NPYG4A', Null, 'CW0001', 'NORMAL', getdate(), '2                                   ','OPEN','" + desc + "','SELITE', getdate(), 'SELITE',getdate(), 'MYI3EW', 'CASE1', getdate(), '" + evtTile + "', 'OPEN ', 'MYI3EW', 'O70W2B')";
								data[2] = "Insert Into Elitetask (Elitetask_Guid, Objective_Guid, Objectivetype_Id, Expectstarttime, Expectendtime, Priority, Handleby_Id, Handlegroup_Id, Createdby, Createddate, Modifiedby, Modifieddate, Comments, Customer_Guid, Curstepstatus, Curstep_Id, Stepforecastdate, Curstep_Id_Map, Map_Id, Objectivesubstatus, Obflag) Values (Newid(), '" + Relation_ID + "', 'NPYG4A', getdate(), getdate(), 'NORMAL', Null, 'CW0001', 'SELITE', getdate(), 'SELITE', getdate(), '" + desc + "', '2                                   ', 'OPEN ', 'O70W2B', getdate(), 'O70W2B', 'MYI3EW', 'OPEN', '0')";
								data[3] = "Insert Into Workorderstep3 (Workorder_Guid, Workorderstep_Guid, Oldhandleby_Id, Oldhandlegroup_Id, Handleby_Id, Handlegroup_Id, Workorderstepstatus, Comments, Modifieddate,  Stepstart, Cur_Expiredflag, Cur_Expiredlen, Event_Guid, From_Stepidmap, To_Stepidmap, Workstarttime, Workendtime) Values ('" + Relation_ID + "', Newid(), 'SELITE', 'SYSTEM', '', 'CW0001', 'CLOSE', '" + desc + "', getdate(),getdate(), '0', '0', '', 'O70W2B', 'O70W2B', getdate(),getdate())";

								log.debug("当前工单编号不存在新建结果SQL:" + data.toString());
								def dataresult = eliteBean.updateBatch(data, "dataSource");
								log.debug("当前工单编号不存在新建结果SQL结果:" + dataresult.toString());
						}else if(old_Relation_ID != null&&objectivestatus=='CLOSE'&&(workorder_state=='7'||(workorder_state=='4'&&resultstatus==1))){//客服系统回退、完结，城管重新派遣
							String[] data = new String[9];
							data[0] = "Insert Into TABCCONSULTWORKORDER_His Select Newid(),* From TABCCONSULTWORKORDER Where Relation_Id = '" + old_Relation_ID + "'";
							data[1] = "update TABCCONSULTWORKORDER  set workorder_state='5' where Relation_ID = '" + old_Relation_ID + "'";
							data[2] ="insert into TABCCONSULTWORKORDER_His(HISGUID,RELATION_ID,business_source,case_type,case_region,case_id,surplus_time,come_time,case_describe,disposal_object,disposal_process,address,location_x,location_y,limit_time,actinstid,wfinstid,evtID,workorder_state)VALUES(Newid(),'" + old_Relation_ID + "','9999B1','" + className + "','" + mapName + "','" + evtTile + "','" + jdSyStr + "','" + inDate + "','" + desc + "','" + lastzrdw + "','" + activityName + "','" + address + "','" + baidu_x + "','" + baidu_y + "','" + limit + "','" + actinstid + "','" + wfinstid + "','" + evtID + "','5')";
							data[3] = "Delete From Workorderpath3 Where Workorder_Guid = '" + old_Relation_ID + "' And From_Stepidmap = 'O70W2B' And To_stepidmap = 'KNGZL4'";
							data[4] = "delete From Objective where Objective_Guid='" + old_Relation_ID + "'";
							data[5] = "Insert Into Objective (Objective_Guid, Objectivetype_Id, Handleby_Id, Handlegroup_Id, Priority_Id, Expireddate, Customer_Guid, Objectivestatus,comments, Createdby, Createddate, Modifiedby, Modifieddate, Workorderframe_Id, Category, Forecastdate, Workorderid, Objectivesubstatus, Map_Id, Curstep_Id_Map) Values ('" + old_Relation_ID + "', 'NPYG4A', Null, 'CW0001', 'NORMAL', getdate(), '2                                   ','OPEN','" + desc + "','SELITE', '"+createddate+"', 'SELITE',getdate(), 'MYI3EW', 'CASE1', getdate(), '" + evtTile + "', 'OPEN ', 'MYI3EW', 'O70W2B')";
							data[6] = "Insert Into Elitetask (Elitetask_Guid, Objective_Guid, Objectivetype_Id, Expectstarttime, Expectendtime, Priority, Handleby_Id, Handlegroup_Id, Createdby, Createddate, Modifiedby, Modifieddate, Comments, Customer_Guid, Curstepstatus, Curstep_Id, Stepforecastdate, Curstep_Id_Map, Map_Id, Objectivesubstatus, Obflag) Values (Newid(), '" + old_Relation_ID + "', 'NPYG4A', getdate(), getdate(), 'NORMAL', Null, 'CW0001', 'SELITE', '"+createddate+"', 'SELITE', getdate(), '" + desc + "', '2                                   ', 'OPEN ', 'O70W2B', getdate(), 'O70W2B', 'MYI3EW', 'OPEN', '0')";
							data[7] = "Insert Into Workorderstep3 (Workorder_Guid, Workorderstep_Guid, Oldhandleby_Id, Oldhandlegroup_Id, Handleby_Id, Handlegroup_Id, Workorderstepstatus, Comments, Modifieddate,  Stepstart, Cur_Expiredflag, Cur_Expiredlen, Event_Guid, From_Stepidmap, To_Stepidmap, Workstarttime, Workendtime) Values ('" + old_Relation_ID + "', Newid(), 'SELITE', 'SYSTEM', '', 'CW0001', 'AGAIN ', '" + desc + "', getdate(),getdate(), '0', '0', '', 'O70W2B', 'O70W2B', getdate(),getdate())";
							data[8] = "delete From rm_uploadrecord where objectiveID='" + old_Relation_ID + "' and type=1";
						
							log.debug("当前工单编号已经存在,执行重新派遣更新结果SQL:" + data.toString());
							def dataresult = eliteBean.updateBatch(data,  "dataSource");
							log.debug("当前工单编号已经存在,执行重新派遣更新结果SQL结果:" + dataresult.toString());
							log.debug("当前工单编号已经存在,执行重新派遣更新结果,dataresult:" + dataresult);
							
							//处理前附件列表 1  type 处理前
							for (int j = 0; j < beforeImgJsonArray.length(); j++) {
								JSONObject beforeImgJson = beforeImgJsonArray.getJSONObject(j);
								beforeImgevtID = GetJV(beforeImgJson, "evtID");
								beforeImgfileUrl = GetJV(beforeImgJson, "fileUrl");
								beforeImgfileID = GetJV(beforeImgJson, "fileID");
								eliteBean.update("insert into rm_uploadrecord(guid,objectiveID,path,name,operator,operationtime,filedesc,type)VALUES(NEWID(),'" + old_Relation_ID + "','" + beforeImgfileUrl + "','" + beforeImgevtID + "','数字化城管',GETDATE(),'" + beforeImgfileID + "','1')", "dataSource");
							}
							//处理后附件列表 2  type 处理后
							for (int j = 0; j < afterImgJsonArray.length(); j++) {
								JSONObject afterImgJson = afterImgJsonArray.getJSONObject(j);
								afterImgevtID = GetJV(afterImgJson, "evtID");
								afterImgfileUrl = GetJV(afterImgJson, "fileUrl");
								afterImgfileID = GetJV(afterImgJson, "fileID");
								eliteBean.update("insert into rm_uploadrecord(guid,objectiveID,path,name,operator,operationtime,filedesc,type)VALUES(NEWID(),'" + old_Relation_ID + "','" + afterImgfileUrl + "','" + afterImgevtID + "','数字化城管',GETDATE(),'" + afterImgfileID + "','2')", "dataSource");
							}
							
						}else{//更新处理剩余时限、环节时限
							String[] data = new String[1];
							data[0] = "update TABCCONSULTWORKORDER  set surplus_time='" + jdSyStr + "',limit_time='" + limit + "',actinstid='" + actinstid + "' where Relation_ID = '" + old_Relation_ID + "'";
							log.debug("当前工单编号已经存在,执行时限更新结果SQL:" + data.toString());
							def dataresult = eliteBean.updateBatch(data,  "dataSource");
							log.debug("当前工单编号已经存在,执行时限更新SQL结果:" + dataresult.toString());
							log.debug("当前工单编号已经存在,执行时限更新结果,dataresult:" + dataresult);
						}
					}
					//生成处理完成时间
					rendTime = System.currentTimeMillis();
				}
				// 包装拼接返回JSONObject
				log.debug(logPrefix + "同步案件调用问题处理时长(毫秒):" + (rendTime - rstartTime)+"，接口返回："+errorMsg);

			} catch (JSONException e) {
				rendTime = System.currentTimeMillis();
				log.error(logPrefix + "处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (rendTime - rstartTime));
			}
			if(count>100*PageIndex) {
				PageIndex++;
			}else {
				onofftype=false;
			}
			
		}
		
	}

	// 获取token
	public static String getCaseTasks(EliteBean eliteBean) {
		log.debug("-------------------------start Bp_Get_CGToKen 开始-----------------");
		def sysurl = "http://127.0.0.1:8080/EliteGeneralHttpTask/GeneralService/Bp_Get_CGToKen";
		String reJson = Util.doHttpGet(sysurl, "UTF-8", 100000, 0);
		JSONObject inObject = new JSONObject(reJson);
		log.debug("ToKen报文："+reJson);

		String resultcode = KHUtil.GetJV(inObject, "resultcode");
		String data = KHUtil.GetJV(inObject, "data");
		log.debug("resultcode	"+resultcode);
		log.debug("data	"+data);
		
		return data;
	}
	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		return Rev_Value;
	}

}